package arithmetic.multithread;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 线程间通信方式三
 * @author lidd
 *
 */
public class Thread3 {

	public static void main(String[] args) {

		final Printer2 print = new Printer2();

		new Thread() {
			public void run() {
				while(true) {
					try {
						print.print1();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}.start();

		new Thread() {
			public void run() {
				while(true) {
					try {
						print.print2();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}.start();

		new Thread() {
			public void run() {
				while(true) {
					try {
						print.print3();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}.start();
	}

}

class Printer2{
	private int flag = 1;
	private ReentrantLock r = new ReentrantLock();
	Condition c1 = r.newCondition();
	Condition c2 = r.newCondition();
	Condition c3 = r.newCondition();

	public void print1() throws InterruptedException {
		r.lock();
		if(flag != 1) {
			c1.await();
		}
		System.out.print("哈");
		System.out.print("哈");
		System.out.print("哈");
		System.out.print("哈");
		System.out.print("哈");
		System.out.print("哈");
		System.out.println("\r\n");
		flag = 2;
		c2.signal();
		r.unlock();
	}

	public void print2() throws InterruptedException {
		r.lock();
		if(flag != 2) {
			c2.await();
		}
		System.out.print("呵");
		System.out.print("呵");
		System.out.print("呵");
		System.out.print("呵");
		System.out.print("呵");
		System.out.print("呵");
		System.out.println("\r\n");
		flag = 3;
		c3.signal();
		r.unlock();
	}

	public void print3() throws InterruptedException {
		r.lock();
		if(flag != 3) {
			c3.await();
		}
		System.out.print("啦");
		System.out.print("啦");
		System.out.print("啦");
		System.out.print("啦");
		System.out.print("啦");
		System.out.print("啦");
		System.out.println("\r\n");
		flag = 1;
		c1.signal();
		r.unlock();
	}
}